<?php 

if (empty($_POST['password'])) die;

//check the captcha_code 
if (!empty($_SESSION['securimage'])) {
	require_once 'inc/securimage/securimage.php';
	$securimage = new Securimage();
	if (!$securimage->check(filter_var($_POST['captcha_code'], FILTER_SANITIZE_EMAIL))) {
		clean_remember_password();
		put_info('验证码错误！^_^');
		header('Location:?c=user&a=login');
		die();
	}			
}

$username = filter_var($_POST['username'], FILTER_SANITIZE_EMAIL);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);

//记住密码
if (!empty($_POST['remember_password'])) {
	setcookie('user_username', $username, time()+3600*24*30, '/');
	setcookie('user_password', $password, time()+3600*24*30, '/');
}

if (empty($username) || empty($password)) {
	put_info('用户名 或 密码 为空！^_^');
	header('Location:?c=user&a=register');
	die();
}

$user = dt_query_one("SELECT id, username FROM user WHERE (username = '$username' AND password = '".$password."') OR (email = '$username' AND password = '".$password."')");
if (!$user) {
	put_info('登录失败！^_^');
	$_SESSION['securimage'] = 'Y';
	header('Location:?c=user&a=login');
	die();
}

$user_info = dt_query_one("SELECT name FROM user_info WHERE id = ".$user['id']);
if (!$user_info) {
	//初始化user_info
	$user_name = '用户'.$user['id'];
	$rs = dt_query("INSERT INTO user_info (id, name, c_at) VALUES ('".$user['id']."', '$user_name', ".time().")");
	if (!$rs) die('新建user_info数据失败！^_^');
} else {
	$user_name = $user_info['name'];
}

$_SESSION['auth'] = array(
	'id' => $user['id'],
	'name' => $user_name);

$_SESSION['securimage'] = null;

//如果是首次登录,跳去初始化account
if (!$user_info) { header('Location:?c=account&a=index'); die(); }

//检查是否有新的订单
$has_order = dt_query_one("SELECT id FROM forum_topic WHERE user_id = ".$user['id']." AND order_c > 0 LIMIT 1");
if ($has_order) {
	$_SESSION['user_has_order'] = 1;
}

//如果cookie里保存了login_jump,跳转过去
if (!empty($_COOKIE['login_jump'])) {
	//Get the cookie
	$login_jump = filter_var($_COOKIE['login_jump'], FILTER_SANITIZE_URL);
	setcookie('login_jump', '', time()-3600, '/');
	header('Location:'.$login_jump);
	die();
}

header('Location:?c=center');
die();
